/*
	© Simone Esposito - 2013
*/

using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour {
	// wheel colliders
	public WheelCollider colFL;
	public WheelCollider colFR;
	public WheelCollider colRL;
	public WheelCollider colRR;
	
	// center of mass
	public GameObject centerOfMass;
	
	// car settings
	public float maxSteer;
	public float maxThrottle;
	public float maxBrake;
	public float drive;
	
	// engine audio clip
	private AudioSource engineSound;
	
	// internal variables: public for debugging
	public float steer = 0;
	public float throttle = 0;
	public float brake = 0;

	void Start(){
		// set center of mass
		rigidbody.centerOfMass = centerOfMass.transform.localPosition;
		
		// init and play engine sound
		engineSound = this.gameObject.audio;
		engineSound.Play();
	}
	
	void ResetCar() {
		transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
		transform.position = new Vector3(0, 0, 0);
		rigidbody.velocity = Vector3.zero;
		rigidbody.angularVelocity = Vector3.zero;
	}
	
	void Update() {
		// reset car
		if ((Input.GetButtonDown("ResetCar")) || (transform.position.y<-40)) 
			ResetCar();
		}
		
	void FixedUpdate() {
		// get inputs
 		steer = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1);
		throttle = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1);
		brake = -1 * Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
		
		// steer
		colFL.steerAngle = maxSteer * steer;
		colFR.steerAngle = maxSteer * steer;

		// accelerate
		float acc = (throttle>0) ? throttle : -brake;
		if (drive<=0.5f) { // rear wheels
			colRL.motorTorque = maxThrottle * acc;
			colRR.motorTorque = maxThrottle * acc;
		}
		if (drive>=0.5f) { // front wheels
			colFL.motorTorque = maxThrottle * acc;
			colFR.motorTorque = maxThrottle * acc;
		}
		
		// brake
		if (throttle>0)	{
			colRL.brakeTorque = maxBrake * brake;
			colRR.brakeTorque = maxBrake * brake;
			colFL.brakeTorque = maxBrake * brake;
			colFR.brakeTorque = maxBrake * brake;
		}
	}	
	
	void LateUpdate() {
		// get current wheels rpm mean value
		float rpm = (colFL.rpm + colFR.rpm + colRL.rpm + colRR.rpm)/4;
		
		// modify engine sound pitch
		engineSound.pitch = Mathf.Clamp((rpm/2 + throttle)/750, 0.25f, 2.0f);
	}
}
